package com.css.zfzx.sjcj.modules.hddcGeomorphySvyReProf.service.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.css.zfzx.sjcj.common.utils.EasyPoiExcelUtil;
import com.css.zfzx.sjcj.common.utils.UpdateUtil;
import com.css.zfzx.sjcj.modules.hddcFaultSvyPoint.repository.entity.HddcFaultsvypointEntity;
import com.css.zfzx.sjcj.modules.hddcGeologicalSvyPoint.repository.entity.HddcGeologicalsvypointEntity;
import com.css.zfzx.sjcj.modules.hddcGeomorphySvyReProf.repository.HddcGeomorphysvyreprofNativeRepository;
import com.css.zfzx.sjcj.modules.hddcGeomorphySvyReProf.repository.HddcGeomorphysvyreprofRepository;
import com.css.zfzx.sjcj.modules.hddcGeomorphySvyReProf.repository.entity.HddcGeomorphysvyreprofEntity;
import com.css.zfzx.sjcj.modules.hddcGeomorphySvyReProf.service.HddcGeomorphysvyreprofService;
import com.css.zfzx.sjcj.modules.hddcGeomorphySvyReProf.viewobjects.HddcGeomorphysvyreprofQueryParams;
import com.css.zfzx.sjcj.modules.hddcGeomorphySvyReProf.viewobjects.HddcGeomorphysvyreprofVO;
import com.css.bpm.platform.api.local.PlatformAPI;
import com.css.bpm.platform.sys.dict.repository.entity.DictItemEntity;
import com.css.bpm.platform.utils.*;
import com.css.zfzx.sjcj.modules.hddcGeomorphySvyRegion.repository.entity.HddcGeomorphysvyregionEntity;
import com.css.zfzx.sjcj.modules.hddcGeomorphySvyRegion.service.HddcGeomorphysvyregionService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * @author zyb
 * @date 2020-11-30
 */
@Service
public class HddcGeomorphysvyreprofServiceImpl implements HddcGeomorphysvyreprofService {

	@Autowired
    private HddcGeomorphysvyreprofRepository hddcGeomorphysvyreprofRepository;
    @Autowired
    private HddcGeomorphysvyreprofNativeRepository hddcGeomorphysvyreprofNativeRepository;
    @Autowired
    private HddcGeomorphysvyregionService hddcGeomorphysvyregionService;

    @Override
    public JSONObject queryHddcGeomorphysvyreprofs(HddcGeomorphysvyreprofQueryParams queryParams, int curPage, int pageSize,String sort,String order) {
        Page<HddcGeomorphysvyreprofEntity> hddcGeomorphysvyreprofPage = this.hddcGeomorphysvyreprofNativeRepository.queryHddcGeomorphysvyreprofs(queryParams, curPage, pageSize, sort, order);
        JSONObject jsonObject = PlatformPageUtils.formatPageData(hddcGeomorphysvyreprofPage);
        return jsonObject;
    }


    @Override
    public HddcGeomorphysvyreprofEntity getHddcGeomorphysvyreprof(String id) {
        HddcGeomorphysvyreprofEntity hddcGeomorphysvyreprof = this.hddcGeomorphysvyreprofRepository.findById(id).orElse(null);
         return hddcGeomorphysvyreprof;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HddcGeomorphysvyreprofEntity saveHddcGeomorphysvyreprof(HddcGeomorphysvyreprofEntity hddcGeomorphysvyreprof) {
        String uuid = UUIDGenerator.getUUID();
        hddcGeomorphysvyreprof.setUuid(uuid);
        hddcGeomorphysvyreprof.setCreateUser(PlatformSessionUtils.getUserId());
        hddcGeomorphysvyreprof.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
        hddcGeomorphysvyreprof.setIsValid("1");
        this.hddcGeomorphysvyreprofRepository.save(hddcGeomorphysvyreprof);
        return hddcGeomorphysvyreprof;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HddcGeomorphysvyreprofEntity updateHddcGeomorphysvyreprof(HddcGeomorphysvyreprofEntity hddcGeomorphysvyreprof) {
        UpdateUtil.copyNullProperties(hddcGeomorphysvyreprofRepository.findByUuidAndIsValid(hddcGeomorphysvyreprof.getUuid(), "1"), hddcGeomorphysvyreprof);
        hddcGeomorphysvyreprof.setUpdateUser(PlatformSessionUtils.getUserId());
        hddcGeomorphysvyreprof.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
        this.hddcGeomorphysvyreprofRepository.save(hddcGeomorphysvyreprof);
        return hddcGeomorphysvyreprof;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteHddcGeomorphysvyreprofs(List<String> ids) {
        List<HddcGeomorphysvyreprofEntity> hddcGeomorphysvyreprofList = this.hddcGeomorphysvyreprofRepository.findAllById(ids);
        if(!PlatformObjectUtils.isEmpty(hddcGeomorphysvyreprofList) && hddcGeomorphysvyreprofList.size() > 0) {
            for(HddcGeomorphysvyreprofEntity hddcGeomorphysvyreprof : hddcGeomorphysvyreprofList) {
                hddcGeomorphysvyreprof.setIsValid("0");
                hddcGeomorphysvyreprof.setUpdateUser(PlatformSessionUtils.getUserId());
                hddcGeomorphysvyreprof.setUpdateTime(new Date());
                this.hddcGeomorphysvyreprofRepository.save(hddcGeomorphysvyreprof);
            }
        }
    }

    @Override
    public List<DictItemEntity> getValidDictItemsByDictCode(String dictCode) {
        List<DictItemEntity> validDictItems = PlatformAPI.getDictAPI().getValidDictItemsByDictCode(dictCode);
        return validDictItems;
    }

    @Override
    public void exportFile(HddcGeomorphysvyreprofQueryParams queryParams, HttpServletResponse response) {
        List<HddcGeomorphysvyreprofEntity> yhDisasterEntities = hddcGeomorphysvyreprofNativeRepository.exportYhDisasters(queryParams);
        List<HddcGeomorphysvyreprofVO> list=new ArrayList<>();
        for (HddcGeomorphysvyreprofEntity entity:yhDisasterEntities) {
            HddcGeomorphysvyreprofVO yhDisasterVO=new HddcGeomorphysvyreprofVO();
            BeanUtils.copyProperties(entity,yhDisasterVO);
            list.add(yhDisasterVO);
        }
        EasyPoiExcelUtil.exportExcel(list, "微地貌面测量切线-线", "微地貌面测量切线-线", HddcGeomorphysvyreprofVO.class, "微地貌面测量切线-线.xls", response);
    }

    @Override
    public String exportExcel(MultipartFile file, HttpServletResponse response) {
        try {
            // 返回的消息
            StringBuilder returnMsg = new StringBuilder();
            // 导入的参数信息
            ImportParams params = new ImportParams();
            // 设置简析的第一行
            params.setHeadRows(1);
            // 是否需要校验
            params.setNeedVerify(true);
            // 获取到Excel数据
            ExcelImportResult<HddcGeomorphysvyreprofVO> result = ExcelImportUtil.importExcelMore(file.getInputStream(), HddcGeomorphysvyreprofVO.class, params);
            List<HddcGeomorphysvyreprofVO> list = result.getList();
            // Excel条数据
            int firstList = list.size();
            StringBuilder sb = new StringBuilder();
            //保存
            saveDisasterList(list, sb);
            returnMsg.append("成功导入" + (result.getList().size() ));
            returnMsg.append(sb);
            if (result.isVerifyFail()) {
                // 校验返回失败行信息
                Iterator<HddcGeomorphysvyreprofVO> iterator = result.getFailList().iterator();
                while (iterator.hasNext()) {
                    HddcGeomorphysvyreprofVO yhDisasterVO = iterator.next();
                    String error = "";
                    returnMsg.append("第" + yhDisasterVO.getRowNum() + "行" + yhDisasterVO.getErrorMsg() + "<br/>");
                    returnMsg.append(error);
                }
            }
            return returnMsg.toString();
        } catch (Exception e) {

            return "导入失败，请检查数据正确性";
        }
    }

    @Override
    @Transactional
    public int wdmdataQualityCheck() {
        List<HddcGeomorphysvyreprofEntity> listAll = hddcGeomorphysvyreprofRepository.findByAll();
        ArrayList<String> list = new ArrayList<>();
        for (HddcGeomorphysvyreprofEntity b2All: listAll) {
            String str="";
            if (StringUtils.isEmpty(b2All.getRegionid())) {
                continue;
            }
            HddcGeomorphysvyregionEntity hddcGeomorphysvyregionEntity =  hddcGeomorphysvyregionService.findById(b2All.getRegionid());
            if (hddcGeomorphysvyregionEntity==null){
                hddcGeomorphysvyreprofRepository.updateStatus("2", "质检失败", b2All.getUuid());
                continue;
            }
            if (!hddcGeomorphysvyregionEntity.getGeomorphysvyprjid().equals(b2All.getGeomorphysvyprjid()) ) {
                str += "微地貌测量工程编号失败.";
            }
            if(str.isEmpty()){
                str +="质检成功";
                hddcGeomorphysvyreprofRepository.updateStatus("1",str,b2All.getUuid());
            }else{
                hddcGeomorphysvyreprofRepository.updateStatus("2",str,b2All.getUuid());
            }
        }
        return 1;
    }

    /**
     * 批量存入库表并且返回错误数量
     *
     * @param list
     * @param message
     * @return
     */
    public void saveDisasterList( List<HddcGeomorphysvyreprofVO> list, StringBuilder message) {
        for (int i = 0; i < list.size(); i++) {
            HddcGeomorphysvyreprofEntity yhDisasterEntity = new HddcGeomorphysvyreprofEntity();
            HddcGeomorphysvyreprofVO yhDisasterVO = list.get(i);
            // 将VO数据映射拷贝到库表中
            BeanUtils.copyProperties(yhDisasterVO, yhDisasterEntity);
            saveHddcGeomorphysvyreprof(yhDisasterEntity);
        }
    }


}
